package ua.keeper.query;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class WeekListAdapter extends ArrayAdapter<WeekListItem>
{
	private ArrayList<WeekListItem> listItems_;
	private Context context_;
	
    /*****************************************************************************************/
	public WeekListAdapter(Context context, int textViewResourceId, ArrayList<WeekListItem> items)
	{
        super(context, textViewResourceId, items);
        context_ = context;
        listItems_ = items;
	}

    /*****************************************************************************************/
	@Override
    public View getView(int position, View convertView, ViewGroup parent)
	{
        View v = convertView;
        if (v == null)
        {
			LayoutInflater vi = (LayoutInflater) context_.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        v = vi.inflate(R.layout.week_list_row, null);
        }
    	WeekListItem item = listItems_.get(position);
    	if (item != null)
        {
	        TextView tvTitle = (TextView) v.findViewById(R.id.weekTitleView);
	        TextView tvCount = (TextView) v.findViewById(R.id.weekCountView);
	        TextView tvPlan = (TextView) v.findViewById(R.id.weekPlanView);
	        ProgressBar pBar = (ProgressBar) v.findViewById(R.id.progressBar);
	        
	        if (tvTitle != null)
	        {
	        	tvTitle.setText(item.getTitle());
	        }
	        if (tvCount != null)
	        {
	        	tvCount.setText(strPre(item.getDaySumm()) + " (" +
	        			Integer.toString(item.getClientQ()) + ")");
	        }
	        if (tvPlan != null)
	        {
	        	tvPlan.setText(strPre(item.getPlanSumm()));
	        	pBar.setMax((int) Math.round(item.getPlanSumm()));
	        }
	        if (pBar != null)
	        {
	        	pBar.setProgress((int) Math.round(item.getDaySumm()));
	        }
	        // if there is last one
	        if (item.getDayId() == 7)
	        {
	        	ImageView image = (ImageView) v.findViewById(R.id.weekIcon);
	        	image.setImageResource(R.drawable.query);
	        	pBar.setVisibility(4);
	        	tvPlan.setVisibility(4);
	        }
        }
    	else
        {
			TextView tvTitle = (TextView) v.findViewById(R.id.weekTitleView);
			tvTitle.setText("<ERROR>");
		}
    	return v;
    }
	
	/*****************************************************************************************/
	private String strPre(double inValue)
	{
		DecimalFormat threeDec = new DecimalFormat("0.00");
		threeDec.setGroupingUsed(false);
		return threeDec.format(inValue);
	}
}